import 'dart:async';
import 'package:aitao_flutter/routes/routes.dart';
import 'package:aitao_flutter/utils/sp_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:netease_corekit_im/im_kit_client.dart';
import 'package:nim_core/nim_core.dart';

class IMManager extends ChangeNotifier {
  String imAppKey = '5b303c2e5e45b1384ab3ce0f2d7d5b5c';
  int _unReadCount = 0;

  int get unReadCount => _unReadCount;

  static IMManager? _instance;
  final subsriptions = <StreamSubscription>[];
  //单例模式，只创建一次实例
  static IMManager? getInstance() {
    if (_instance == null) {
      _instance = IMManager();
      return _instance;
    }
    return _instance;
  }

  getIMUnReadCount() async {
    final result =
        await NimCore.instance.messageService.queryTotalUnreadCount();
    if (result.isSuccess) {
      debugPrint('获取系统消息未读总数量:${result.data}');
      _unReadCount = result.data ?? 0;
      notifyListeners();
    }
  }

  initIM() {
    NIMIOSSDKOptions iosOption = NIMIOSSDKOptions(appKey: imAppKey);
    IMKitClient.init(imAppKey, iosOption).then((success) {
      if (success) {
        debugPrint('ios im init success');
        if (SpUtil.getImToken() != '') {
          String account = SpUtil.getLoginUserInfo().userId.toString();
          String token = SpUtil.getImToken();
          imLogin(account, token);
        }
      } else {
        debugPrint('ios im init error');
      }
    }).catchError((e) {
      debugPrint('ios IMKitClient init catchError:$e');
    });

    NIMAndroidSDKOptions androidOptions =
        NIMAndroidSDKOptions(appKey: imAppKey);
    IMKitClient.init(imAppKey, androidOptions).then((success) {
      if (success) {
        debugPrint('android im init success');
        if (SpUtil.getImToken() != '') {
          String account = SpUtil.getLoginUserInfo().userId.toString();
          String token = SpUtil.getImToken();
          imLogin(account, token);
        }
      } else {
        debugPrint('android im init error');
      }
    }).catchError((e) {
      debugPrint('android IMKitClient init catchError:$e');
    });

    // subsriptions
    //     .add(NimCore.instance.messageService.onMessagePinNotify.listen((event) {
    //   print('MessageService##receive message pin: $event ');
    // }));

    // subsriptions.add(
    //     NimCore.instance.messageService.onStickTopSessionAdd.listen((session) {
    //   print('MessageService##onStickTopSessionAdd: $session ');
    // }));

    // subsriptions.add(NimCore.instance.messageService.onStickTopSessionUpdate
    //     .listen((session) {
    //   print('MessageService##onStickTopSessionUpdate: $session ');
    // }));

    // subsriptions.add(NimCore.instance.messageService.onStickTopSessionRemove
    //     .listen((session) {
    //   print('MessageService##onStickTopSessionRemove: $session ');
    // }));

    // subsriptions.add(
    //     NimCore.instance.messageService.onSyncStickTopSession.listen((session) {
    //   print('MessageService##onSyncStickTopSession: ${session.join('##')} ');
    // }));

    // subsriptions.add(
    //     NimCore.instance.messageService.onQuickCommentAdd.listen((comment) {
    //   print('MessageService##onQuickCommentAdd: $comment');
    // }));

    // subsriptions.add(
    //     NimCore.instance.messageService.onQuickCommentRemove.listen((comment) {
    //   print('MessageService##onQuickCommentRemove: $comment');
    // }));

    // subsriptions.add(
    //     NimCore.instance.messageService.onMySessionUpdate.listen((session) {
    //   print('MessageService##onMySessionUpdate: $session');
    // }));

    // subsriptions
    //     .add(NimCore.instance.messageService.onSessionDelete.listen((session) {
    //   print('MessageService##onSessionDelete: $session');
    // }));

    // subsriptions
    //     .add(NimCore.instance.messageService.onSessionUpdate.listen((session) {
    //   print('MessageService##onSessionUpdate: $session');
    // }));
  }

  imLogin(account, token) {
    IMKitClient.loginIM(NIMLoginInfo(account: account, token: token))
        .then((success) {
      if (success) {
        //登录成功
        debugPrint('IM Login Success');

        subsriptions
            .add(NimCore.instance.authService.authStatus.listen((event) {
          debugPrint('监听到登录状态事件流:${event.status.name}');
          if (event.status == NIMAuthStatus.kickOut ||
              event.status == NIMAuthStatus.kickOutByOtherClient) {
            //被其他端的登录踢掉 && 被其他端的登录踢掉
            EasyLoading.showToast('账号被踢下线');
            SpUtil.cleanUserInfo();
            Get.offAllNamed(Routes.smsCodeLoginPage);
          }
        }));

        // subsriptions
        //     .add(NimCore.instance.messageService.onMessage.listen((messages) {
        //   debugPrint('监听到消息');
        //   for (var message in messages) {
        //     debugPrint(
        //         '消息发送方昵称: ${message.fromNickname} 消息文本  ${message.content}');
        //   }
        // }));

        // subsriptions.add(NimCore
        //     .instance.systemMessageService.onCustomNotification
        //     .listen((event) {
        //   debugPrint('接收到系统自定义通知:${event.toString()}');
        //   //   飘屏字段content 12
        //   /// ios判断是否在前台运行
        // if (SpUtil.getAppLifeState()) {
        //   debugPrint('App在前台运行');
        // } else {
        //   debugPrint('App在后台运行');
        // }
        // }));

        // subsriptions.add(NimCore
        //     .instance.systemMessageService.onReceiveSystemMsg
        //     .listen((event) {
        //   debugPrint('接收到系统消息通知:${event.toString()}');
        // }));
      } else {
        //登录失败
        debugPrint('IM Login Error');
      }
    });
  }
}
